// NODEJS  commonjs 规范   require()   module.exports 或者exports 抛出模块
let Koa = require('koa');

let app = new Koa();

let fs = require('fs');

//需求：1.获取每次请求花费时间  endTime - startTime 

app.use(async (ctx,next) => {
    console.log(ctx.path);
    // console.log(ctx.url);
    // console.log(ctx.request.method);
    // ctx.body = 'hello world';
    let startTime = new Date().getTime();
    console.log("第一个中间件开始");
    await next();
    console.log("第一个中间件结束");
    let endTime = new Date().getTime();
    let time = endTime - startTime;
    //路径-请求方式-请求状态-耗时（以毫秒为单位）
    ctx.body = `本次请求花费${time}`;
    fs.appendFileSync('./log.log',`${ctx.path}-${ctx.method}-${ctx.status}-${time}/n`);
})

app.use(async (ctx,next) => {
    console.log("===第二个中间件开始");
    await next();
    console.log("第二个中间件结束")
})

function delay(){
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve();
        },1000)
    })
}


app.use(async (ctx,next) => {
    console.log("第三个中间件开始");
    await delay();
    await next();
    console.log("第三个中间件结束")
})

app.listen(3000,() => {
    console.log("服务器启动成功")
})